<script setup name="YTree">
const { proxy } = getCurrentInstance();

const props = defineProps({
  api: { type: Function },
  showSearch: { type: Boolean, default: true },
  showCheckTools: { type: Boolean, default: false },
});

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

const modelValue = ref();
const loading = ref(false);
const treeRef = ref(null);
const treeData = ref(null);
const nodeExpand = ref(true);
const nodeSelectAll = ref(false);
const nodeCheckStrictly = ref(true);

/** 树权限（展开/折叠）*/
function handleNodeExpand(value) {
  let treeList = treeData.value;
  for (let i = 0; i < treeList.length; i++) {
    treeRef.value.store.nodesMap[treeList[i].id].expanded = value;
  }
}

/** 树权限（全选/全不选） */
function handleNodeSelectAll(value) {
  treeRef.value.setCheckedNodes(value ? treeData.value : []);
}

/** 树权限（父子联动） */
function handleNodeCheckStrictly(value) {
  nodeCheckStrictly.value = value ? true : false;
}

function initTree() {
  loading.value = true;
  props.api().then((res) => {
    treeData.value = res.data;
    loading.value = false;
    if (proxy.$attrs.modelValue) {
      proxy.$attrs.modelValue.forEach((v) => {
        nextTick(() => {
          treeRef.value.setChecked(v, true, false);
        });
      });
    }
  });
}

initTree();
</script>
<template>
  <div>
    <el-input
      v-if="showSearch"
      prefix-icon="Search"
      clearable
      v-bind="$attrs"
    />
    <div v-if="showCheckTools">
      <el-checkbox v-model="nodeExpand" @change="handleNodeExpand($event)"
        >展开/折叠</el-checkbox
      >
      <el-checkbox v-model="nodeSelectAll" @change="handleNodeSelectAll($event)"
        >全选/全不选</el-checkbox
      >
      <el-checkbox
        v-model="nodeCheckStrictly"
        @change="handleNodeCheckStrictly($event)"
        >父子联动
      </el-checkbox>
    </div>
    <el-tree
      ref="treeRef"
      v-loading="loading"
      node-key="id"
      :data="treeData"
      :filter-node-method="filterNode"
      :props="{ value: 'id', label: 'label', children: 'children' }"
      :check-strictly="!nodeCheckStrictly"
      :expand-on-click-node="false"
      highlight-current
      default-expand-all
      v-bind="$attrs"
    />
  </div>
</template>
